﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WXR2BlogML
{
	/// <summary>
	/// http://prettycode.org/2009/05/07/hexadecimal-value-0x-is-an-invalid-character/
	/// </summary>
	public class XmlSanitizedString
	{
		private readonly string _value;

		public XmlSanitizedString(string s)
		{
			_value = SanitizeXmlString(s);
		}

		/// <summary>
		/// Get the XML-santizied string.
		/// </summary>
		public override string ToString()
		{
			return _value;
		}

		/// <summary>
		/// Remove illegal XML characters from a string.
		/// </summary>
		private static string SanitizeXmlString(string xml)
		{
			if (string.IsNullOrEmpty(xml))
			{
				return xml;
			}

			var buffer = new StringBuilder(xml.Length);

			foreach (char c in xml)
			{
				if (IsLegalXmlChar(c))
				{
					buffer.Append(c);
				}
			}

			return buffer.ToString();
		}

		/// <summary>
		/// Whether a given character is allowed by XML 1.0.
		/// </summary>
		private static bool IsLegalXmlChar(int character)
		{
			return
			(
				  character == 0x9 /* == '\t' == 9   */        ||
				  character == 0xA /* == '\n' == 10  */        ||
				  character == 0xD /* == '\r' == 13  */        ||
				 (character >= 0x20 && character <= 0xD7FF) ||
				 (character >= 0xE000 && character <= 0xFFFD) ||
				 (character >= 0x10000 && character <= 0x10FFFF)
			);
		}
	}
}
